package cn.edu.gzist.chapter09spring.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Service
public class DynamicTaskService {
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    // 保存任务数据
    private final Map<String,ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();
    // 创建任务
    public void addCronTask(String taskId, String cronExpression, Runnable task) {
        CronTrigger cronTrigger = new CronTrigger(cronExpression);
        ScheduledFuture<?> future =  threadPoolTaskScheduler.schedule(task,cronTrigger);
        scheduledTasks.put(taskId,future);
    }
    // 取消任务
    public boolean cancelTask(String taskId ) {
        ScheduledFuture<?> future = scheduledTasks.get(taskId);
        if (future != null) {
            boolean cancel = future.cancel(true);
            if (cancel) {
                scheduledTasks.remove(taskId);
            }
            return cancel;
        }
        return false;
    }
    public Set<String> getAllTaskId(){
        return scheduledTasks.keySet();
    }
}
